<?php

if (!function_exists('object2array')) {
    /**
     * 对象转数组
     * @param $object
     * @return mixed
     * @author shixu
     * Date 2018/12/6
     */
    function object2array($object)
    {
        if (is_object($object)) return json_decode(json_encode($object), true);
        return $object;
    }
}
if (!function_exists('create_rand')) {
    /**
     * 生成固定位数的随机字符串
     * @param $len 需要生成的位数
     * @param bool $is_int 是否是纯数字
     * @param bool $is_word 是否纯字母
     * @return string
     */
    function create_rand($len, $is_int = false, $is_word = false)
    {
        if ($is_int) {
            $str = '0123456789';
            $str_len = 9;
        } elseif ($is_word) {
            $str = 'abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ';
            $str_len = 49;
        } else {
            $str = 'abcdefghjklmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
            $str_len = 55;
        }
        $result = '';
        for ($i = 1; $i <= $len; $i++) {
            //如果需要的是数字类型则第一位不能是零
            if ($i == 1) {
                $start = mt_rand(1, $str_len);
            } else {
                $start = mt_rand(0, $str_len);
            }
            $result .= substr($str, $start, 1);
        }
        return $result;
    }
}

if (!function_exists('createOrderNumber')) {
    /**
     * 生成订单号 （日期6+时间戳11+随机字符串3）
     * @param $len 需要生成的位数
     * @param bool $is_int 是否是纯数字
     * @param bool $is_word 是否纯字母
     * @return string
     */
    function createOrderNumber()
    {
        $result = date('ymd') . time() . rand(100, 999);

        return $result;
    }
}

if (!function_exists('getImgColor2')) {
    /**
     * 获取图片颜色方法 2
     * @param $img_url 图片路径
     * @return string
     */
    function getImgColor2($img_url)
    {
        $imageInfo = getimagesize($img_url);

        //图片类型
        $imgType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));

        //对应函数
        $imageFun = 'imagecreatefrom' . ($imgType == 'jpg' ? 'jpeg' : $imgType);

        $i = $imageFun($img_url);

        //循环色值
        $rColorNum = $gColorNum = $bColorNum = $total = 0;

        for ($x = 0; $x < imagesx($i); $x++) {

            for ($y = 0; $y < imagesy($i); $y++) {

                $rgb = imagecolorat($i, $x, $y);

                //三通道
                $r = ($rgb >> 16) & 0xFF;

                $g = ($rgb >> 8) & 0xFF;

                $b = $rgb & 0xFF;

                $rColorNum += $r;

                $gColorNum += $g;

                $bColorNum += $b;

                $total++;
            }
        }

        $rgb = array();

        $rgb[0] = round($rColorNum / $total);
        $rgb[1] = round($gColorNum / $total);
        $rgb[2] = round($bColorNum / $total);

        return $rgb;
    }
}


if (!function_exists('sendPostFun')) {
    /**
     * POST Curl异步请求
     * @param array $data 数据集
     * @param string $host url地址
     * @param array $header http头部信息
     * @return string
     */
    function sendPostFun($host = '', $data = [], $header = null)
    {
        $ch = curl_init();

        if ($header) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            curl_setopt($ch, CURLOPT_HEADER, 0);//返回response头部信息
        }

        curl_setopt($ch, CURLOPT_URL, $host);

        // 返回结果
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_HEADER, 0);

        // 使用POST提交
        curl_setopt($ch, CURLOPT_POST, 1);

        // POST参数
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        // 结果
        $res = curl_exec($ch);

        curl_close($ch);

        return json_decode($res, true);
    }
}

if (!function_exists('phoneDecrypt')) {
    /**
     * RSA私钥解密
     * @param array $data 数据集
     * @param string $host url地址
     * @param array $header http头部信息
     * @return string
     */
    function phoneDecrypt($phone = '', $prikey = null)
    {
        $prefix = '-----BEGIN RSA PRIVATE KEY-----';
        $suffix = '-----END RSA PRIVATE KEY-----';
        $result = '';

        $encrypted = $phone;

        $key = $prefix . "\n" . $prikey . "\n" . $suffix;
        openssl_private_decrypt(base64_decode($encrypted), $result, openssl_pkey_get_private($key));

        return $result;
    }
}

if (!function_exists('createStrCode')) {
    /**
     * 生成字符串单号
     * @param bool $check_number 是否纯数字
     * @return string
     */
    function createStrCode($check_number = true)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

        $str = $chars[rand(0, strlen($chars))];

        $numbers = time() . rand(1000, 9999);

        if (!$check_number) {
            $numbers = $str . $numbers;
        }

        return $numbers;
    }
}

if (!function_exists('timeToLastDay')) {
    function timeToLastDay($time)
    {
        return ceil(($time - strtotime(date('Y-m-d'))) / (60 * 24 * 60));
    }
}


if (!function_exists('ajaxSuccess')) {

    /**
     * ajax成功输出
     * @param array $data
     * @param string $message
     * @author guoyong at 2017-03-02
     */
    function ajaxSuccess($data = [], $message = 'success')
    {
        output(0, $message, $data, true);
    }
}
if (!function_exists('ajaxError')) {

    /**
     * ajax失败输出
     * @param int $errCode
     * @param string $message
     * @param array $data
     * @author guoyong at 2017-03-02
     */
    function ajaxError($message = '', $errCode = 1, $data = [])
    {
        $err = explode("|", $message);
        if (is_array($err) && count($err) > 1) {
            $message = $err[1];
            $errCode = $err[0];
        }
        output($errCode, $message, $data, true);
    }
}

if (!function_exists('output')) {

    /**
     * api接口结果统一输出
     * @param string $errCode 错误码 0代表无错误
     * @param string $message 提示信息
     * @param array $data 扩展数据
     * @param bool $ajax ajax输出
     * @return array
     * @author guoyong at 2017-03-01
     */
    function output($errCode, $message, $data = [], $ajax = false, $exit = true)
    {
        $data = ['errCode' => $errCode, 'message' => $message, 'data' => $data, 'time' => time()];
        if ($ajax) {
            header('Content-Type:application/json;charset=utf-8');
            echo json_encode($data, JSON_UNESCAPED_UNICODE);
            if ($exit)
                exit;
        }
        return $data;
    }
}
if (!function_exists('error')) {

    /**
     * 操作失败
     * @param string $message
     * @param int $errCode
     * @param array $data
     * @return array
     * @author guoyong at 2017-03-01
     */
    function error($message = '', $errCode = 1, $data = [])
    {
        $err = explode("|", $message);
        if (is_array($err) && count($err) > 1) {
            $message = $err[1];
            $errCode = $err[0];
        }
        return output($errCode, $message, $data);
    }
}
if (!function_exists('success')) {
    /**
     * 操作成功
     * @param array $data
     * @return array
     * @author guoyong at 2017-03-01
     */
    function success($data = [], $message = 'success')
    {
        return output(0, $message, $data);
    }
}
if (!function_exists('isAjax')) {
    /**
     * 判断是否ajax请求
     * @return boolean
     */
    function isAjax()
    {
        return (
                !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') || strpos(strtolower($_SERVER['HTTP_ACCEPT']), 'json') != false;
    }
}
if (!function_exists('createPwd')) {

    function createPwd($string)
    {
        return md5(md5('mgm_20_2021' . md5($string)));
    }
}

if (!function_exists('getExcelFileData')) {
    /**
     * 读取excel文件
     * @param $rowKey = ['A' => 'name' , 'B' => 'mobile']
     * @return [['name'=>'' , 'mobile'=>'']]
     */
    function getExcelFileData($file, $rowKey = [], $startRowLine = 1, $sheetIndex = 0): array
    {
        $speradsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
        $sheet = $speradsheet->getSheet($sheetIndex);
        $highestRow = $sheet->getHighestRow();
        $arr = [];
        for ($startRowLine; $startRowLine <= $highestRow; $startRowLine++) {
            $data = [];
            foreach ($rowKey as $k => $v) {
                $data[$v] = trim($sheet->getCell($k . $startRowLine)->getValue());
            }
            $arr[] = $data;
        }
        return $arr;
    }
}

if (!function_exists('arrayToXml')) {
    /**
     * 将数组转换为xml格式数据
     * @param array $arr 要转换的数组
     * @return string
     * @author guoyong at 2017-03-01
     */
    function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_array($val)) {
                $xml .= "<" . $key . ">" . _arrayToXml($val) . "</" . $key . ">";
            } elseif (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }
}

if (!function_exists('xmlToArray')) {
    /**
     * 将XML转换为数组
     * @param string $xml
     * @return array
     * @author guoyong at 2017-03-01
     */
    function xmlToArray($xml)
    {
        $arr = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        return json_decode(json_encode($arr), true);
    }

}

if (!function_exists('getClientIp')) {
    /**
     * 获取客户端IP地址
     * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
     * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
     * @return mixed
     */
    function getClientIp($type = 0, $adv = false)
    {
        $type = $type ? 1 : 0;
        static $ip = null;
        if ($ip !== null) {
            return $ip[$type];
        }
        if ($adv) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos = array_search('unknown', $arr);
                if (false !== $pos) {
                    unset($arr[$pos]);
                }
                $ip = trim($arr[0]);
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u", ip2long($ip));
        $ip = $long ? [$ip, $long] : ['0.0.0.0', 0];
        return $ip[$type];
    }
}
if (!function_exists('opensslEncrypt')) {
    /**
     * 公共函数
     */
    function opensslEncrypt($str, $key = '', $iv = '', $method = 'aes-128-cbc', $options = 0)
    {
        if (empty($key)) $key = config('app')['openssKey'];
        if (empty($iv)) $iv = config('app')['openssIv'];
        return openssl_encrypt($str, $method, $key, $options, $iv);
    }
}
if (!function_exists('opensslDecrypt')) {

    function opensslDecrypt($str, $key = '', $iv = '', $method = 'aes-128-cbc', $options = 0)
    {
        if (empty($key)) $key = config('app')['openssKey'];
        if (empty($iv)) $iv = config('app')['openssIv'];
        return openssl_decrypt($str, $method, $key, $options, $iv);
    }
}
if (!function_exists('exportSvc')) {
    /**
     * 导出svc
     * @param string $fileName [文件名称]
     * @param array $data [数据集]
     */
    function exportSvc($data = [], $fileName)
    {
        set_time_limit(0);
        header('Content-Type: application/vnd.ms-execl');
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');
        header('Cache-Control: max-age=0');
        $fp = fopen('php://output', 'a');
        $index = 0;
        foreach ($data as $row) {
            foreach ($row as $k => $val) {
                $row[$k] = iconv('UTF-8', 'GBK//IGNORE', "\t" . $val);
            }
            fputcsv($fp, $row);
            $index += 1;
            if ($index == 10000) {
                ob_flush();
                flush();
                $index = 0;
            }
        }
        exit;

    }
}
